from etgui import *
from PageLayout import gTabSheetStyle,ShowSubDialog,PotTextField,MakeOkCancelDialog
from ListEditor import AbstrListEditor
from CmdNo import cIdOk

class AbstrModelDictEditor(AbstrListEditor):
	"""A class that does simple list editing"""
	def __init__(self,model,path):
		self.path=path
		self.model=None
		self.items=[]
		AbstrListEditor.__init__(self)
		if model:
			self.SetItems(model)
	def MakePath(self,slot):
		if self.path and slot:
			return self.path+"."+slot
		elif slot:
			return slot
		else:
			return self.path
	def SplitPath(self,path):
		p=self.path+"."
		if p==path[:len(p)]:
			return path[len(p):]
		return path
	def PathAt(self,i):
		try:
			key= self.items[i]
		except IndexError:
			key= ""
		return self.MakePath(key)
	def KeyAt(self,i):
		try:
			return self.items[i]
		except IndexError:
			return None
	def KeyPos(self,item):
		try:
			return self.items.index(item)
		except ValueError:
			return -1
	def Reload(self,select_key=None):
		if select_key is None:
			select_key=self.KeyAt(self.GetSelected())
		self.SetItems(self.model)
		i=self.KeyPos(select_key)
		if i>=0:
			self.Select(i)
	###XXX TBD use a PotGuiVObj to do the observing!!!
	def Observe(self,model,path):
		#print 'Observe',self._GetCollView().IsOpen(), `path`
		if path==self.path:
			self.ObserveReload(model,path)
	def Open(self,mode):
		if mode:
			self.Reload()
	def ObserveReload(self,model,path):
		self.SetItems(Cast(model))
 
	def IsUniqueName(self,name):
		return self.items.count(name)==0

	def FindUniqueName(self,name):
		n=name
		i=1
		while i<100 and not self.IsUniqueName(n):
			n=self.MakeName(name,i)
			i=i+1
		return n
 
	def DoSetItems(self,model):
		if self.model is None:
			self.model=model
			model.AddModelObserver(self.Observe,self.path,self._GetCollView())
		self.items=self.GetIndex()
		return self.items
	def GetIndex(self):
		items=self.model.GetIndex(self.path)
		if items is None:
			items=[]
		items.sort()
		return items
	def DoMakeItem(self,key_value):
		try:
			key,value=key_value
		except (TypeError,ValueError):
			key=key_value
		return TextItem(str(key))
 
	def DoInsert(self,i,key_value):
		key,value=key_value
		k=-1
		for k in range(len(self.items)):
			if self.items[k]>key:
				break
		else:
			k=k+1
		self.items.insert(k,key)
		self.model.SetValue(self.MakePath(key),value)
		return k
	def DoDelete(self,i):
		key=self.items[i]
		del self.items[i]
		return self.model.RemoveAt(self.MakePath(key))

class SimpleModelDictEditor(AbstrModelDictEditor):
	def __init__(self,model,path,what):
		self.what=what
		AbstrModelDictEditor.__init__(self,model,path)
	def DoNew(self,i):
		value=self.NewValue()
		key_value=(self.FindUniqueName("NewItem"),value)
		return self.EditName("New",key_value)
	def DoCopy(self,i):
		key=self.items[i]
		value=self.model.GetValue(self.MakePath(key))
		key_value=(self.FindUniqueName(key),value)
		return self.EditName("Copy",key_value)
	def DoRename(self,i):
		key=self.items[i]
		value=self.model.GetValue(self.MakePath(key))
		key_value=(key,value)
		return self.EditName("Rename",key_value)
 
	def NewValue(self):
		return "???"
 
	def MakeName(self,name,i):
		return "%s%i" %(name,i)
 
	def RenameValue(self,value,newname):
		# rename the slot Name
		try:
			if value["Name"] is not None:
				value["Name"]=newname
		except:
			pass
		return value
	def EditName(self,how,key_value):
		key,value=key_value
		m=PotGuiModel()
		m.SetValue("Name",key)
		retval=ShowSubDialog("%s %s" %(how,self.what),
			m,
			PotTextField("Name")
		)
		newkey=m.GetValue("Name")
		value=self.RenameValue(value,newkey)
 
		if retval and not self.IsUniqueName(newkey) and newkey!=key:
			ShowAlert(eAlertNote,"The name @B%s@B already exists!" %repr(newkey))
			return None
		if retval:
			newkey=m.GetValue("Name")
			if newkey and '.' in newkey:
				ShowAlert(eAlertNote,"The character '.' (dot) is @bnot@b allowed in a name!")
				return self.EditName(how,(newkey,value))
			return (newkey,value)
		else:
			return None

class ModelDictEditor(SimpleModelDictEditor):
	"""Controler for edit in File Type"""
	slotpath='?'
	itemdialog=None
	# method that is called when user wants to set defauts
	# of currently selected item
	SetDefaults=None
	def __init__(self,model,path,what):
		self.submodel=PotGuiSubModel(path,model)
		# disable the submodel initially
		self.submodel.SetValue("PSEUDO.Prefix","?")
		SimpleModelDictEditor.__init__(self,model,path,what)
	def Slot(self,name):
		return self.slotpath+"."+name
	def MakeName(self,name,i):
		import regsub
		name=regsub.sub('-[0-9]+$','',name)
		return "%s-%i" %(name,i)
	def DoSelect(self,i):
		if i>=0:
			self.slotpath=self.MakePath(self.items[i])
		else:
			self.slotpath='?'
		self.SelectionChanged()
	def DoEdit(self,i):
		label=""
		if gTabSheetStyle:
			label= " Properties"
		title="%s `%s`%s" %(self.what,self.items[i],label)
		if not self.itemdialog:
			view=self.MakeItemEditView()
			self.itemdialog=MakeOkCancelDialog(title,EditPotGuiModel(self.submodel),view)
		self.itemdialog.SetName(title)
		if self.itemdialog.ShowUnderMouse()==cIdOk:
			self.DoEditDone()
	def DoEditDone(self):
		pass
	def MakePreview(self):
		return ModelContainer(self.submodel,self.DoMakePreview(self.submodel))
	def MakeItemEditView(self):
		return ModelContainer(self.submodel,self.DoMakeItemEditView(self.submodel))
	def SelectionChanged(self):
		self.submodel.SetValue("PSEUDO.Prefix",self.slotpath)
 
	# override those methods
	def DoMakePreview(self,model):
		return Filler(gPoint1)
	def DoMakeItemEditView(self,model):
		return Filler(gPoint1)


